package com.meida.module.bus.provider.controller;

import com.meida.common.base.entity.EntityMap;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.utils.DateUtils;
import com.meida.module.bus.client.entity.BusOrder;
import com.meida.module.bus.client.enums.PayStateEnum;
import com.meida.module.bus.provider.service.BusAfterserviceService;
import com.meida.module.bus.provider.service.BusOrderService;
import com.meida.module.pay.client.enums.PayCashoutStatusEnum;
import com.meida.module.pay.provider.service.PayCashoutService;
import com.meida.module.user.provider.service.AppUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;


/**
 * 后台首页统计
 *
 * @author flyme
 * @date 2021-08-03
 */
@RestController
@RequestMapping("/homeTotal/")
public class BusHomeTotalController {

    @Autowired
    private AppUserService appUserService;

    @Autowired
    private PayCashoutService payCashoutService;

    @Autowired
    private BusAfterserviceService busAfterserviceService;

    @Autowired
    private BusOrderService busOrderService;

    @ApiOperation(value = "系统首页统计", notes = "系统首页统计")
    @GetMapping(value = "getTotalInfo")
    public ResultBody getTotalInfo() {
        EntityMap data = new EntityMap();
        //平台总用户
        long totalUserNum = appUserService.count();
        data.put("totalUserNum", totalUserNum);
        //今日新增用户
        long todayUserNum = appUserService.countByDate(DateUtils.formatDate());
        data.put("todayUserNum", todayUserNum);
        //提现成功金额
        BigDecimal cashOutSuccessAmount = payCashoutService.sumCashoutStatus(PayCashoutStatusEnum.success.getValue());
        data.put("cashOutSuccessAmount", cashOutSuccessAmount);
        //提现中金额
        BigDecimal cashOutDealWithAmount = payCashoutService.sumCashoutStatus(PayCashoutStatusEnum.dealWith.getValue());
        data.put("cashOutDealWithAmount", cashOutDealWithAmount);
        //提现总额
        BigDecimal cashOutTotalAmount = cashOutSuccessAmount.add(cashOutDealWithAmount);
        data.put("cashOutTotalAmount", cashOutTotalAmount);
        //退款审核中金额
        BigDecimal refundCheckAmount = busAfterserviceService.sumAmountByState(0);
        data.put("refundCheckAmount", refundCheckAmount);
        //退款金额
        BigDecimal refundAmount = busOrderService.sumPayableAmountByPayState(PayStateEnum.refund.getValue());
        data.put("refundAmount", refundAmount);
        //退款总额
        BigDecimal refundTotalAmount = refundCheckAmount.add(refundAmount);
        data.put("refundTotalAmount", refundTotalAmount);
        //订单总金额
        BigDecimal orderTotalAmount = busOrderService.sumOrderAmountByPayState(PayStateEnum.HavePay.getValue());
        data.put("orderTotalAmount", orderTotalAmount);
        //今日订单金额
        BigDecimal todayTotalAmount = busOrderService.sumOrderAmountByPayState(PayStateEnum.HavePay.getValue(), 1, DateUtils.formatDate());
        data.put("todayTotalAmount", todayTotalAmount);
        //本月订单金额
        String month = DateUtils.getYear() + "-" + DateUtils.getMonth();
        BigDecimal monthTotalAmount = busOrderService.sumOrderAmountByPayState(PayStateEnum.HavePay.getValue(), 2, month);
        data.put("monthTotalAmount", monthTotalAmount);
        return ResultBody.ok(data);
    }

    @ApiOperation(value = "系统首页-图表(折线图)", notes = "系统首页-图表(折线图)")
    @GetMapping(value = "getOrderLineData")
    public ResultBody getOrderLineData(String startDate, String endDate) throws ParseException {
        //分类型统计订单数量,金额
        CriteriaQuery<BusOrder> cq = new CriteriaQuery<>(BusOrder.class);
        cq.addSelect("date_format(createTime,'%Y-%m-%d') date", "count(if(orderType=1,1,null)) orderNum1", "COALESCE(sum(if(orderType=1,orderAmount,0)),0) totalAmount1");
        cq.addSelect("count(if(orderType=2,1,null)) orderNum2", "COALESCE(sum(if(orderType=2,orderAmount,0)),0) totalAmount2");
        cq.addSelect("count(if(orderType=3,1,null)) orderNum3", "COALESCE(sum(if(orderType=3,orderAmount,0)),0) totalAmount3");
        cq.ge("date_format(createTime,'%Y-%m-%d')", startDate);
        cq.le("date_format(createTime,'%Y-%m-%d')", endDate);
        cq.eq("payState", PayStateEnum.HavePay.getValue());
        cq.groupBy("createTime");
        List<EntityMap> list = busOrderService.selectEntityMap(cq);
        List<String> xData = findDates(startDate, endDate);
        List<Integer> y11Data = new ArrayList<>();
        List<BigDecimal> y12Data = new ArrayList<>();
        List<Integer> y21Data = new ArrayList<>();
        List<BigDecimal> y22Data = new ArrayList<>();
        List<Integer> y31Data = new ArrayList<>();
        List<BigDecimal> y32Data = new ArrayList<>();
        for (String x : xData) {
            int y11 = 0;
            BigDecimal y12 = BigDecimal.ZERO;
            int y21 = 0;
            BigDecimal y22 = BigDecimal.ZERO;
            int y31 = 0;
            BigDecimal y32 = BigDecimal.ZERO;
            for (EntityMap item : list) {
                if (x.equals(item.get("date"))) {
                    y11 = item.getInt("orderNum1");
                    y12 = item.getBigDecimal("totalAmount1");
                    y21 = item.getInt("orderNum2");
                    y22 = item.getBigDecimal("totalAmount2");
                    y31 = item.getInt("orderNum3");
                    y32 = item.getBigDecimal("totalAmount3");
                }
            }
            y11Data.add(y11);
            y12Data.add(y12);
            y21Data.add(y21);
            y22Data.add(y22);
            y31Data.add(y31);
            y32Data.add(y32);
        }
        EntityMap data = new EntityMap();
        data.put("xData", xData);
        data.put("y11Data", y11Data);
        data.put("y12Data", y12Data);
        data.put("y21Data", y21Data);
        data.put("y22Data", y22Data);
        data.put("y31Data", y31Data);
        data.put("y32Data", y32Data);
        return ResultBody.ok(data);
    }

    /**
     * 获取一段日期所有日期
     *
     * @param dBegin 开始时间
     * @param dEnd   结束时间
     * @return
     * @throws ParseException
     */
    public List<String> findDates(String dBegin, String dEnd) throws ParseException {
        if (FlymeUtils.isEmpty(dBegin)) {
            dBegin = DateUtils.formatDate();
        }
        if (FlymeUtils.isEmpty(dEnd)) {
            dEnd = DateUtils.formatDate();
        }
        //日期工具类准备
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        //设置开始时间
        Calendar calBegin = Calendar.getInstance();
        calBegin.setTime(format.parse(dBegin));
        //设置结束时间
        Calendar calEnd = Calendar.getInstance();
        calEnd.setTime(format.parse(dEnd));
        //装返回的日期集合容器
        List<String> datelist = new ArrayList<String>();
        // 每次循环给calBegin日期加一天，直到calBegin.getTime()时间等于dEnd
        while (format.parse(dEnd).equals(calBegin.getTime()) || format.parse(dEnd).after(calBegin.getTime())) {
            // 根据日历的规则，为给定的日历字段添加或减去指定的时间量
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            datelist.add(format.format(calBegin.getTime()));
        }
        return datelist;
    }
}
